<template>
  <div>
    <div :style="{ borderBottom: '1px solid #E9E9E9' }">
      <a-modal
        v-model="visible"
        title="编辑"
        ok-text="确认"
        cancel-text="取消"
        @ok="saveAs"
      >
        <div>名称:<a-input v-model="itemEdited.name"></a-input></div>
        <div id="wrap">
          <a-checkbox-group
            :disabled="!isEdit && !isNew"
            v-model="itemEdited.items"
            :options="optionList"
          />
        </div>
      </a-modal>
      <a-space>
        <a-select
          style="width: 100px"
          v-model="curTemplateName"
          default-value="不过滤"
          @change="onSelect"
        >
          <a-select-option
            v-for="item in templates"
            :key="item.name"
            :value="item.name"
            >{{ item.name }}</a-select-option
          >
        </a-select>
        <a-button @click="refreshTemplates"> 刷新 </a-button>
        <a-button @click="toDev" v-if="!setDisabled"> 下发当前设备 </a-button>

        <a-button
          :disabled="!curTemplateName || curTemplateName == '全部'"
          @click="edit"
        >
          编辑
        </a-button>
        <a-button @click="add">新增</a-button>
        <a-button
          @click="del"
          :disabled="!curTemplateName || curTemplateName == '全部'"
          >删除</a-button
        >
        <!--<a-button @click="toAll"> 应用所有设备 </a-button>-->
      </a-space>
    </div>
    <div id="wrap">
      <a-checkbox-group
        style="font-size: 40px"
        :disabled="true"
        v-model="checkedOptions"
        :options="optionList"
      />
      <div style="margin-top: 20px; margin-left: 0">
        当前全局模板:<span>{{ gTemplateName }}</span>
      </div>
    </div>
  </div>
</template>
<script>
/*0, //重合闸跳闸; 
1~10：保留
11, // 重合闸通信; 
12, //电源板掉线
13, //电源板电压 欠压/过高
14, // 电源板 Outlet 电流 过高
15, //电源板 Outlet 继电器出错
16, //220V 过压/欠压; 
17, // DC12V 过压/欠压;
18, //AC24V 过压/欠压;
19, //SMbus 出错
20, // 温度
21, // 湿度
22, // 机箱 ACC 倾斜
23, // 机箱震动;
24, // 摄像头掉线; 
25, //风扇转速过低
26, // 水浸; 
27, // 防雷设备失效
28, //烟雾发生
29, // =1 未授权 开箱门是否授权
30, //电子锁 未上锁
31, // 保留*/
const options = [
  { name: "重合闸通讯", id: 11 },
  { name: "电源板掉线", id: 12 },
  { name: "电源板电压", id: 13 },
  { name: "电源板电流", id: 14 },
  { name: "电源板继电器出错", id: 15 },
  { name: "市电", id: 16, checked: false },
  { name: "DC12V", id: 17 },
  { name: "AC24V", id: 18 },
  { name: "SMbus 出错", id: 19 },
  { name: "温度", id: 20 },
  { name: "湿度", id: 21 },
  { name: "机箱 ACC 倾斜", id: 22 },
  { name: "机箱震动", id: 23 },
  // {name:'',id:'',checked:true},
  { name: "风扇转速过低", id: 25 },
  { name: "水浸", id: 26 },
  { name: "防雷设备失效", id: 27 },
  { name: "烟雾", id: 28 },
  { name: "未授权开门", id: 29 },
  { name: "电子锁未上锁", id: 30 },
  { name: "频闪灯", id: -1 },
  { name: "照明灯", id: -2 },
  { name: "告警灯", id: -3 },
  { name: "蜂鸣器", id: -4 },
  { name: "加热器", id: -5 },
  { name: "风扇", id: -6 },
  { name: "电流", id: -7 },
  { name: "漏电流", id: -8 },
  { name: "门", id: -9 },
];
import {
  getMObj,
  modifyMObj,
  removeMObj,
  forceTemplate,
  getTemplate,
} from "@/services/mobj.js";
import { ctrlService } from "@/services/ctrl.js";
export default {
  props: ["setDisabled"],
  data() {
    return {
      checkedOptions: [],
      optionList: [],
      indeterminate: true,
      templates: [],
      curTemplateName: "全部",
      gTemplateName: "",
      //curTemplate:{},
      itemEdited: {},
      isNew: true,
      isEdit: true,
      visible: false,
    };
  },
  created() {
    let self = this;
    self.defalutOptions = [];
    self.checkedOptions = [];
    options.forEach((o) => {
      self.optionList.push(o.name);
      self.checkedOptions.push(o.name);
    });
    self.refreshTemplates();
  },

  methods: {
    add() {
      this.isEdit = false;
      this.isNew = true;
      this.itemEdited = { name: "新建", items: [] };
      this.visible = true;
    },
    edit() {
      this.isEdit = true;
      this.isNew = false;
      let template = this.templates.find((t) => {
        return t.name == this.curTemplateName;
      });
      if (template) {
        this.itemEdited = Object.assign({}, template);
      }
      this.visible = true;
    },
    del() {
      if (this.gTemplateName == this.curTemplateName) {
        this.$notification["error"]({
          message: "提示",
          description: "全局使用的模板不能删除",
          placement: "topLeft",
        });
        return;
      }
      let self = this;
      //let templates = Object.assign([],this.templates)
      let index = this.templates.findIndex((t) => {
        return t.name == self.curTemplateName;
      });
      if (index >= 0) {
        this.templates.splice(index, 1);
        this.save();
      }
    },
    onCheckAllChange(e) {
      this.checkedOptions = Object.assign([], this.optionList);
    },
    onSelect() {
      let template = this.templates.find((t) => {
        return t.name == this.curTemplateName;
      });
      if (!template && this.templates.length > 0) {
        template = this.templates[0];
      }
      if (template) {
        this.curTemplateName = template.name;
        this.checkedOptions = template.items;
      }
    },
    saveAs() {
      if (this.isEdit) {
        let index = this.templates.findIndex((t) => {
          return t.name == this.curTemplateName;
        });
        if (index >= 0) {
          this.templates[index] = this.itemEdited;
        }
      } else {
        this.templates.push(this.itemEdited);
      }
      this.save();
      this.visible = false;
    },
    init() {
      if (!this.templates || this.templates.length == 0) {
        this.templates = [
          {
            name: "全部",
            items: this.optionList,
          },
        ];
        this.save();
      }
    },
    refreshTemplates() {
      let self = this;
      getMObj("sm_templates")
        .then((res) => {
          if (res) {
            if (typeof res == "string") {
              let jobj = JSON.parse(res);
              if (jobj && jobj.body) {
                self.templates = jobj.body.filter((obj) => {
                  return obj != null && obj != undefined;
                });
              }
            } else {
              self.templates = res.body.filter((obj) => {
                return obj != null && obj != undefined;
              });
            }
          }
        })
        .finally(() => {
          getMObj("sm_default_template").then((res) => {
            if (typeof res == "string") {
              let jobj = JSON.parse(res);
              if (jobj && jobj.body) {
                self.gTemplateName = jobj.body.name;
              }
            } else {
              self.gTemplateName = res?.body?.name;
            }
            self.curTemplateName = self.gTemplateName
              ? self.gTemplateName
              : "全部";
            self.init();
            self.onSelect();
          });
        });
    },
    save() {
      if (this.templates) {
        let mobj = {
          s_name: "sm_templates",
          body: this.templates,
        };
        let self = this;
        modifyMObj(mobj).then(() => {
          self.refreshTemplates();
        });
      }
    },
    isIn(op) {
      if (this.checkedOptions) {
        return this.checkedOptions.find((p) => {
          return p === op.name;
        });
      }
      return undefined;
    },
    ctrl(tid, isToAll) {
      let params = "";
      if (this.checkedOptions) {
        let first = true;
        options.forEach((op) => {
          let cp = this.checkedOptions.find((name) => {
            return name == op.name;
          });
          if (!cp) {
            if (op.id < 0) {
              return;
            }
            if (first) {
              params += op.id;
              first = false;
            } else {
              params += "," + op.id;
            }
          }
        });
      }
      /*

        this.checkedOptions.forEach((name) => {
          let op = options.find((o) => {
            return o.name == name;
          });
          /*let nbit = 0
          if(!op){
            return
          }
          let part = 0
          if(typeof op.id == 'string'){
            nbit = Number(op.id)
          }else{
            nbit = op.id
          }
          part = 1 << (nbit-1)
          params += part*/
      /*
          if (first) {
            params += op.id;
            first = false;
          } else {
            params += "," + op.id;
          }
        });
      }*/
      let cmdparam = "";
      if (params.toString() == "") {
        cmdparam = { Mask: [] };
      } else {
        cmdparam = { Mask: params.toString() };
      }
      let path;
      if (isToAll) {
        tid = "ALL";
        cmdparam["ToAll"] = "ALL";
        let self = this;
        let mobj = {
          s_name: "sm_default_template",
          body: {
            options: options.filter((p) => {
              return self.isIn(p);
            }),
            name: self.curTemplateName,
          },
        };
        modifyMObj(mobj).then(() => {
          forceTemplate();
        });
        console.log("save--------------mobj", mobj);
        path = "box";
      }

      ctrlService(tid, "SetSysMask", cmdparam, path)
        .then(() => {
          this.$success({
            title: "成功",
            // JSX support
            content: "控制成功",
          });
        })
        .catch(() => {
          this.$error({
            title: "失败",
            content: "控制失败",
          });
        });
      setTimeout(() => {
        this.$store.dispatch("thingView/refreshActiveThing");
      }, 2000);
    },
    toDev() {
      this.ctrl(this.$store.state.thingView.activeThing.tid);
    },
    toAll() {
      this.ctrl(this.$store.state.thingView.activeThing.tid, true);
    },
  },
};
</script>
<style scoped>
#wrap {
  display: flex;
  flex-wrap: wrap;
  width: 50%;
  margin: 0 10px 0 10px;
}
</style>